package org.com.blbl.ChargeRate;

import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;

import java.io.IOException;
import java.text.DecimalFormat;

public class ChargeRateReducer extends Reducer<Text, Text, Text, Text> {


    @Override
    protected void reduce(Text key, Iterable<Text> values, Reducer<Text, Text, Text, Text>.Context context) throws IOException, InterruptedException {

        double totalCharge = 0;
        double totalFans = 0;

        for (Text value : values) {
            String[] counts = value.toString().split(",");
            totalCharge += Double.parseDouble(counts[0]);
            totalFans += Double.parseDouble(counts[1]);
        }


        double realizeRate = (totalCharge / totalFans);

        DecimalFormat df = new DecimalFormat("0.00%");
        String formattedRate = df.format(realizeRate);


        context.write(key, new Text(formattedRate));
    }
}
